<template>
  <view class="payment-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">订单支付</text>
    </view>

    <!-- 订单信息 -->
    <view class="order-info-section">
      <view class="section-header">
        <text class="section-title">订单信息</text>
      </view>
      
      <view class="order-content">
        <view class="order-item">
          <text class="item-label">订单号</text>
          <text class="item-value">{{ orderId }}</text>
        </view>
        <view class="order-item">
          <text class="item-label">订单金额</text>
          <text class="item-value amount">¥{{ orderAmount }}</text>
        </view>
        <view class="order-item">
          <text class="item-label">创建时间</text>
          <text class="item-value">{{ createTime }}</text>
        </view>
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="payment-method-section">
      <view class="section-header">
        <text class="section-title">支付方式</text>
      </view>
      
      <view class="payment-methods">
        <view 
          class="payment-item" 
          :class="{ active: selectedPayment === 'wechat' }"
          @tap="selectPayment('wechat')"
        >
          <view class="payment-info">
            <image class="payment-icon" src="/static/icons/wechat-pay.png" mode="aspectFit"></image>
            <text class="payment-name">微信支付</text>
          </view>
          <view class="payment-radio" :class="{ checked: selectedPayment === 'wechat' }">
            <text class="radio-dot" v-if="selectedPayment === 'wechat'"></text>
          </view>
        </view>
        
        <!-- 可以添加更多支付方式 -->
        <!-- <view 
          class="payment-item" 
          :class="{ active: selectedPayment === 'alipay' }"
          @tap="selectPayment('alipay')"
        >
          <view class="payment-info">
            <image class="payment-icon" src="/static/icons/alipay.png" mode="aspectFit"></image>
            <text class="payment-name">支付宝</text>
          </view>
          <view class="payment-radio" :class="{ checked: selectedPayment === 'alipay' }">
            <text class="radio-dot" v-if="selectedPayment === 'alipay'"></text>
          </view>
        </view> -->
      </view>
    </view>

    <!-- 支付说明 -->
    <view class="payment-notice-section">
      <view class="notice-content">
        <text class="notice-title">支付说明</text>
        <text class="notice-text">• 请在30分钟内完成支付，超时订单将自动取消</text>
        <text class="notice-text">• 支付成功后，我们将尽快为您安排发货</text>
        <text class="notice-text">• 如有疑问，请联系客服</text>
      </view>
    </view>

    <!-- 底部支付按钮 -->
    <view class="bottom-actions">
      <view class="amount-summary">
        <text class="pay-label">需支付：</text>
        <text class="pay-amount">¥{{ orderAmount }}</text>
      </view>
      <view class="pay-btn" @tap="startPayment" :class="{ loading: paymentLoading }">
        <text class="btn-text" v-if="!paymentLoading">立即支付</text>
        <text class="btn-text" v-else>支付中...</text>
      </view>
    </view>

    <!-- 支付结果弹窗 -->
    <view class="payment-result-modal" v-if="showResultModal" @tap="closeResultModal">
      <view class="modal-content" @tap.stop>
        <view class="result-icon">
          <text class="icon-text" :class="paymentResult.success ? 'success' : 'error'">
            {{ paymentResult.success ? '✓' : '✗' }}
          </text>
        </view>
        <text class="result-title">{{ paymentResult.title }}</text>
        <text class="result-message">{{ paymentResult.message }}</text>
        
        <view class="result-actions">
          <view class="result-btn" @tap="handleResultAction">
            <text class="result-btn-text">{{ paymentResult.success ? '查看订单' : '重新支付' }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 响应式数据
const orderId = ref('')
const orderAmount = ref('0.00')
const createTime = ref('')
const selectedPayment = ref('wechat')
const paymentLoading = ref(false)
const showResultModal = ref(false)
const paymentResult = ref({
  success: false,
  title: '',
  message: ''
})

// 选择支付方式
const selectPayment = (method) => {
  selectedPayment.value = method
}

// 开始支付
const startPayment = async () => {
  if (paymentLoading.value) return
  
  paymentLoading.value = true
  
  try {
    if (selectedPayment.value === 'wechat') {
      await processWechatPayment()
    } else {
      throw new Error('暂不支持该支付方式')
    }
  } catch (error) {
    console.error('支付失败:', error)
    showPaymentResult(false, '支付失败', error.message || '支付过程中出现错误，请重试')
  } finally {
    paymentLoading.value = false
  }
}

// 处理微信支付
const processWechatPayment = async () => {
  return new Promise((resolve, reject) => {
    // 在真实环境中，这里需要：
    // 1. 调用后端API获取微信支付参数
    // 2. 调用uni.requestPayment进行支付
    
    // 模拟支付流程
    uni.showLoading({
      title: '正在调起支付...',
      mask: true
    })
    
    setTimeout(() => {
      uni.hideLoading()
      
      // 模拟支付结果（在实际开发中删除这部分）
      const isSuccess = Math.random() > 0.3 // 70%成功率
      
      if (isSuccess) {
        // 支付成功，更新订单状态
        updateOrderStatus('paid')
        showPaymentResult(true, '支付成功', '订单支付完成，我们将尽快为您发货')
        resolve()
      } else {
        reject(new Error('用户取消支付或支付失败'))
      }
    }, 2000)
    
    // 真实的微信支付代码示例：
    /*
    // 1. 先调用后端API获取支付参数
    const paymentParams = await api.createWechatPayment({
      orderId: orderId.value,
      amount: orderAmount.value
    })
    
    // 2. 调用微信支付
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: paymentParams.timeStamp,
      nonceStr: paymentParams.nonceStr,
      package: paymentParams.package,
      signType: paymentParams.signType,
      paySign: paymentParams.paySign,
      success: (res) => {
        console.log('支付成功:', res)
        updateOrderStatus('paid')
        showPaymentResult(true, '支付成功', '订单支付完成，我们将尽快为您发货')
        resolve()
      },
      fail: (err) => {
        console.error('支付失败:', err)
        reject(new Error(err.errMsg || '支付失败'))
      }
    })
    */
  })
}

// 更新订单状态
const updateOrderStatus = (status) => {
  try {
    // 这里应该调用后端API更新订单状态
    // await api.updateOrderStatus(orderId.value, status)
    
    // 临时更新本地存储
    let orderList = uni.getStorageSync('orderList') || []
    const orderIndex = orderList.findIndex(order => order.id === orderId.value)
    
    if (orderIndex > -1) {
      orderList[orderIndex].status = status
      orderList[orderIndex].payTime = new Date().toISOString()
      uni.setStorageSync('orderList', orderList)
    }
  } catch (error) {
    console.error('更新订单状态失败:', error)
  }
}

// 显示支付结果
const showPaymentResult = (success, title, message) => {
  paymentResult.value = {
    success,
    title,
    message
  }
  showResultModal.value = true
}

// 关闭结果弹窗
const closeResultModal = () => {
  showResultModal.value = false
}

// 处理结果操作
const handleResultAction = () => {
  closeResultModal()
  
  if (paymentResult.value.success) {
    // 支付成功，跳转到订单详情或订单列表
    uni.redirectTo({
      url: '/pages/order/order'
    })
  } else {
    // 支付失败，可以重新支付
    // 这里可以重新调用支付流程
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  const date = new Date(timeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 生命周期
onLoad((options) => {
  if (options.orderId && options.amount) {
    orderId.value = options.orderId
    orderAmount.value = options.amount
    createTime.value = formatTime(new Date().toISOString())
  } else {
    uni.showToast({
      title: '订单信息错误',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
})
</script>

<style scoped>
.payment-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

/* 页面标题 */
.page-header {
  background: white;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 通用区块样式 */
.order-info-section,
.payment-method-section,
.payment-notice-section {
  background: white;
  margin: 16px;
  border-radius: 12px;
  overflow: hidden;
}

.section-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

/* 订单信息 */
.order-content {
  padding: 0 20px;
}

.order-item {
  padding: 16px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.order-item:last-child {
  border-bottom: none;
}

.item-label {
  font-size: 14px;
  color: #666;
}

.item-value {
  font-size: 14px;
  color: #333;
}

.item-value.amount {
  font-size: 18px;
  color: #FF4444;
  font-weight: bold;
}

/* 支付方式 */
.payment-methods {
  padding: 0 20px;
}

.payment-item {
  padding: 16px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.payment-item:last-child {
  border-bottom: none;
}

.payment-item.active {
  background: rgba(255, 184, 0, 0.05);
}

.payment-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.payment-icon {
  width: 32px;
  height: 32px;
}

.payment-name {
  font-size: 16px;
  color: #333;
}

.payment-radio {
  width: 20px;
  height: 20px;
  border: 2px solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.payment-radio.checked {
  border-color: #FFB800;
}

.radio-dot {
  width: 10px;
  height: 10px;
  background: #FFB800;
  border-radius: 50%;
}

/* 支付说明 */
.notice-content {
  padding: 16px 20px;
}

.notice-title {
  font-size: 14px;
  color: #333;
  font-weight: bold;
  display: block;
  margin-bottom: 8px;
}

.notice-text {
  font-size: 12px;
  color: #666;
  line-height: 1.5;
  display: block;
  margin-bottom: 4px;
}

/* 底部支付按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.amount-summary {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 4px;
}

.pay-label {
  font-size: 14px;
  color: #666;
}

.pay-amount {
  font-size: 20px;
  color: #FF4444;
  font-weight: bold;
}

.pay-btn {
  background: linear-gradient(135deg, #FFB800 0%, #FFA000 100%);
  border-radius: 24px;
  padding: 12px 32px;
  box-shadow: 0 4px 12px rgba(255, 184, 0, 0.3);
  transition: all 0.3s ease;
}

.pay-btn:active {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(255, 184, 0, 0.3);
}

.pay-btn.loading {
  opacity: 0.7;
}

.btn-text {
  font-size: 16px;
  color: white;
  font-weight: bold;
}

/* 支付结果弹窗 */
.payment-result-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 16px;
  padding: 32px 24px 24px;
  margin: 0 32px;
  text-align: center;
  max-width: 300px;
  width: 100%;
}

.result-icon {
  margin-bottom: 16px;
}

.icon-text {
  font-size: 48px;
  font-weight: bold;
}

.icon-text.success {
  color: #4CAF50;
}

.icon-text.error {
  color: #F44336;
}

.result-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8px;
}

.result-message {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  display: block;
  margin-bottom: 24px;
}

.result-actions {
  
}

.result-btn {
  background: linear-gradient(135deg, #FFB800 0%, #FFA000 100%);
  border-radius: 20px;
  padding: 10px 24px;
}

.result-btn-text {
  font-size: 14px;
  color: white;
  font-weight: bold;
}
</style>